package com.itheima.home_work.work3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Test {
    public static void main(String[] args) {
        // 切割文件
        String sourcePath = "D:\\ITCAST\\唐老师\\JavaSE进阶\\day10-IO流（二）\\视频\\12. 打印流.mp4";
        splitFile(sourcePath, 5);
    }

    public static void splitFile(String targetPath, int fileNumber) {
        File file = new File(targetPath);
        int byteSize = (int) Math.ceil(file.length() / fileNumber);
        try (
             // 1. 创建输入输出流
             FileInputStream fis = new FileInputStream(file);
        ) {

            // 2. 循环创建输出流
            int len = -1;
            byte[] bytes = new byte[byteSize];
            for (int i = 0; i < fileNumber; i++) {
                FileOutputStream fos = null;
                try {
                    len = fis.read(bytes);
                    fos = new FileOutputStream(targetPath + "." + i);
                    fos.write(bytes, 0, len);
                } catch (Exception e) {
                    System.out.println("碎片写入异常：" + e.getMessage());
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
            }

        } catch (Exception e) {
            System.out.println("异常：" + e.getMessage());
        }
    }

}
